package com.mamingchao.concurrent.JMH;

import org.apache.commons.lang3.StringUtils;

import java.io.*;

/**
 * Created by mamingchao on 2020/12/7.
 */
public class LoadFile {


    public static void main(String[] args) {
		try {
//			saveToFile(System.currentTimeMillis(), "/Users/mamingchao/Documents/temporary/test.txt");
//
			System.out.println(loadFileContent("/Users/mamingchao/Documents/temporary/test.txt"));
//		} catch (IOException e) {
//			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }


    public static void saveToFile(long content, String filename) throws Exception {

        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(file, false);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        try {
            osw.write(String.valueOf(content));
            osw.flush();
        }finally {
            osw.close();
            fos.close();
        }
    }

    private static long loadFileContent(String filename) throws Exception{

        if (StringUtils.isBlank(filename) ) {
            return 0L;
        }
        File file = new File(filename);
        if (!file.exists()) {
            return 0;
        }

        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String s;
        while ((s = br.readLine()).length() !=0) {
            return Long.valueOf(s);
        }
        isr.close();
        fis.close();


        return 0L;
    }

}
